package com.zhang.controller;

import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.map.MapUtil;
import com.google.code.kaptcha.Producer;
import com.zhang.common.lang.Const;
import com.zhang.common.lang.Result;
import com.zhang.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.security.Principal;
import java.util.UUID;

//认证相关的controller
@RestController
public class AuthController extends BaseController{

    //谷歌的验证码生成工具
    @Autowired
    Producer producer;


    //获取验证码接口
    @GetMapping("/captcha")
    public Result captcha() throws IOException {
        String key = UUID.randomUUID().toString();  //用于识别是哪个用户的验证码
        String code = producer.createText();

        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image,"jpg",outputStream);

        Base64Encoder encoder = new Base64Encoder();
        String str = "data:image/jpeg;base64,";

        String base64Img = str + encoder.encode(outputStream.toByteArray());
        redisUtil.hset(Const.Captcha_Key,key,code,120); //存到redis里面

        return Result.succ(MapUtil.builder().put("key",key).put("captchaImg",base64Img).build());
    }

    //获取用户信息接口
    @GetMapping("/sys/userInfo")
    public Result getUserInfo(Principal principal){ //Principal为Security内置的，可通过它获取登录用户的信息
        SysUser user = sysUserService.getByUsername(principal.getName());

        return Result.succ(MapUtil.builder().put("id",user.getId()).put("username",user.getUsername())
                .put("avatar",user.getAvatar()).map());
    }

    //测试浏览器网页下载文件，与本项目无关
//    @GetMapping("/down")
//    public void downFile(HttpServletResponse response) throws IOException {
//        FileInputStream fileInputStream = new FileInputStream("C:\\Users\\lenovo\\Pictures\\Saved Pictures\\timg.jpg");
//        response.setHeader("Content-Disposition", "attachment;filename=1.jpg"); //下载文件的响应头
//        ServletOutputStream outputStream = response.getOutputStream();
//
//        byte[] bytes = new byte[1024];
//        int len;
//        while((len=fileInputStream.read(bytes)) != -1){
//            outputStream.write(bytes,0,len);
//        }
//        fileInputStream.close();
//        outputStream.close();
//    }
}
